/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * This file contains helper functions for loading images as maps.将图像加载为地图。
 *
 * Author: Brian Gerkey
 */

#include <cstring>
#include <stdexcept>

#include <stdlib.h>
#include <stdio.h>

// We use SDL_image to load the image from disk
#include <SDL/SDL_image.h>

// Use Bullet's Quaternion object to create one from Euler angles  使用Bullet库(物理引擎)从欧拉角创建一个四元素对象。
#include <LinearMath/btQuaternion.h>

#include "map_server/image_loader.h"

// compute linear index for given map coords  计算给定地图坐标的线性索引
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))

namespace map_server{

void
loadMapFromFile(nav_msgs::GetMap::Response* resp, const char* fname, double res, bool negate, double occ_th, double free_th, double* origin, MapMode mode){
  SDL_Surface* img; 

  unsigned char* pixels;
  unsigned char* p;
  unsigned char value;
  int rowstride, n_channels, avg_channels;
  unsigned int i,j;
  int k;
  double occ;
  int alpha;
  int color_sum;
  double color_avg;

  // Load the image using SDL.  If we get NULL back, the image load failed.
  if(!(img = IMG_Load(fname))){ //IMG_Load读取图片
    std::string errmsg = std::string("failed to open image file \"") + std::string(fname) + std::string("\": ") + IMG_GetError();
    throw std::runtime_error(errmsg);
  }

  // Copy the image data into the map structure
  resp->map.info.width = img->w;//图像的宽度
  resp->map.info.height = img->h;//图像的高度
  resp->map.info.resolution = res;//图像的分辨率
  resp->map.info.origin.position.x = *(origin);//地图原点x
  resp->map.info.origin.position.y = *(origin+1);//地图坐标原点y
  resp->map.info.origin.position.z = 0.0;//z值默认填充0(二维地图)
  btQuaternion q;
  // setEulerZYX(yaw, pitch, roll)
  q.setEulerZYX(*(origin+2), 0, 0);// 地图原点角度r,转换成四元素,使用欧拉角初始化一个四元数
  resp->map.info.origin.orientation.x = q.x();
  resp->map.info.origin.orientation.y = q.y();
  resp->map.info.origin.orientation.z = q.z();
  resp->map.info.origin.orientation.w = q.w();

  // Allocate(分配) space to hold the data
  resp->map.data.resize(resp->map.info.width * resp->map.info.height);

  // Get values that we'll need to iterate(迭代) through the pixels 获取我们需要遍历的像素值
  rowstride = img->pitch;//这两个是图像的三个通道？加一个透明度？
  n_channels = img->format->BytesPerPixel;

  // NOTE: Trinary mode still overrides here to preserve existing behavior.注意：三通道模式仍然覆盖此处以保留现有行为。
  // Alpha will be averaged in with color channels when using trinary mode.使用三通道模式时，Alpha 将与颜色通道进行平均。
  if (mode==TRINARY || !img->format->Amask)
    avg_channels = n_channels;
  else
    avg_channels = n_channels - 1;

  // 复制像素数据到地图结构体中，最后通过图片信息计算 rgb 平均值 color_avg，根据计算公式 occ = (255 - color_avg) / 255.0;
  // 计算每个像素的占用概率 occ，TRINARY 模式，如果 occ 大于占用概率阈值 occ_th，则当前像素被占用（用100表示），小于 free_th（用0表示）、不确定（用-1表示）。
  pixels = (unsigned char*)(img->pixels);
  for(j = 0; j < resp->map.info.height; j++){
    for (i = 0; i < resp->map.info.width; i++){
      // Compute mean of RGB for this pixel  计算该像素的 RGB 平均值
      p = pixels + j*rowstride + i*n_channels;
      color_sum = 0;
      for(k=0;k<avg_channels;k++)
        color_sum += *(p + (k));
      color_avg = color_sum / (double)avg_channels;

      if (n_channels == 1)
          alpha = 1;
      else
          alpha = *(p+n_channels-1);
      //这里判断一下是否需要黑白颠倒，即：白色->障碍物，原本是白色地方是可通行区域，黑色是障碍物
      if(negate)
        color_avg = 255 - color_avg;
      //如果是按原始模式，就直接设置[0,255]像素原始值
      if(mode==RAW){
          value = color_avg;
          resp->map.data[MAP_IDX(resp->map.info.width,i,resp->map.info.height - j - 1)] = value;
          continue;
      }


      // If negate is true, we consider blacker pixels free, and whiter
      // pixels occupied.  Otherwise, it's vice versa.  如果 negate 为真，我们认为较黑的像素是空闲的，而较白的像素是被占用的，反之亦然。
      // 计算该像素的占有概率，如当没有障碍物占据时，白色RGB值为255，color_avg为RGB三个通道的平均值
      occ = (255 - color_avg) / 255.0;

      //  将阈值应用于 RGB 均值以确定地图的占用值。 请注意，我们反转像素的图形顺序以生成左下角单元格 (0,0) 的地图。
      // Apply thresholds to RGB means to determine occupancy values for
      // map.  Note that we invert the graphics-ordering of the pixels to
      // produce a map with cell (0,0) in the lower-left corner.
      if(occ > occ_th)
        value = +100;   //占据
      else if(occ < free_th)
        value = 0;      // 自由
      else if(mode==TRINARY || alpha < 1.0)
        value = -1;     // 未知,TRINARY模式
      else {
        double ratio = (occ - free_th) / (occ_th - free_th);
        value = 1 + 98 * ratio; //未知(0,100)　占据和自由阈值之间
      }
      //更新到map中对应像素点数据，所以data中的数据一般是：-1,100,0   可以使用 rsotopic echo /map 看一下结果，可以看到地图数据基本都是由这三个数据组成的，这就是occupancy grid
      // https://charon-cheung.github.io/2019/09/15/%E8%B7%AF%E5%BE%84%E8%A7%84%E5%88%92/%E4%BB%A3%E4%BB%B7%E5%9C%B0%E5%9B%BE/ROS%E5%9C%B0%E5%9B%BE%E8%AF%A6%E8%A7%A3/#nav-msgs-OccupancyGrid
      resp->map.data[MAP_IDX(resp->map.info.width,i,resp->map.info.height - j - 1)] = value;
    }
  }

  SDL_FreeSurface(img); //删除img缓冲区
}

}
